﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;

namespace Adams.Admin.DataAccess.Events
{
    public static class CreateCalendar
    {
        public static Adams.Admin.DataTransfer.Events.CreateCalendar.PageLoad PageLoad(int id)
        {
            var data = new Adams.Admin.DataTransfer.Events.CreateCalendar.PageLoad();
            data.Calendar = new Shared.Entities.Events.Calendar();
            
            using (SqlDataReader dr = DB.RunDataReader(@"
IF (@CalendarID > 0)
BEGIN
    SELECT *
    FROM Events.Calendars
    WHERE CalendarID = @CalendarID
END
", CommandType.Text,
            DB.CreateParameter("@CalendarID", id, SqlDbType.Int)))
            {
                if (id > 0)
                {
                    dr.Read();
                    data.Calendar.ID = dr["CalendarID"].DbInt();
                    data.Calendar.Name = dr["Name"].DbString();
                    data.Calendar.Description = dr["Description"].DbString();
                    data.Calendar.Color = dr["Color"].DbString();
                }
            }

            return data;
        }

        public static void Save(DataTransfer.Events.CreateCalendar.FormInput data)
        {
            DB.Run(@"
IF(@CalendarID > 0)
BEGIN
    UPDATE Events.Calendars SET
        Name = @Name,
        Description = @Description,
        Color = @Color
    WHERE CalendarID = @CalendarID
END
ELSE
BEGIN
    INSERT INTO Events.Calendars (
        Name,
        Description,
        Color)
    VALUES (
        @Name,
        @Description,
        @Color)
END
    ", CommandType.Text,
                     DB.CreateParameter("@CalendarID", data.ID.ToInt()),
                     DB.CreateParameter("@Name", data.Name.ToNString()),
                     DB.CreateParameter("@Description", data.Description.ToNString()),
                     DB.CreateParameter("@Color", data.Color.ToNString()));
        }
    }
}